//
//  ST_LoginForGiftController.swift
//  btvideo
//
//  Created by mac on 2020/9/3.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import SwiftyUserDefaults
import SDWebImageWebPCoder

class ST_LoginForGiftController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(back_image_view)
        back_image_view.snp.makeConstraints { (make) in
            make.width.equalTo(365)
            make.height.equalTo(532)
//            make.top.equalToSuperview().offset(statusBarHeight+26)
            make.center.equalToSuperview()
        }
        
        
        
        view.addSubview(confirm_btn)
        confirm_btn.snp.makeConstraints { (make) in
            make.width.equalTo(200)
            make.height.equalTo(44)
            make.bottom.equalTo(back_image_view).offset(-28)
            make.centerX.equalToSuperview()
        }
        

        back_image_view.addSubview(daysLabel)
        daysLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(176)
            make.centerX.equalToSuperview()
        }
        
        
        
        back_image_view.addSubview(giftView1)
        giftView1.snp.makeConstraints { (make) in
            make.width.equalTo(60)
            make.height.equalTo(77)
            make.left.equalToSuperview().offset(48)
            make.top.equalTo(daysLabel.snp.bottom).offset(20)
        }
        
        
        back_image_view.addSubview(giftView2)
        giftView2.snp.makeConstraints { (make) in
            
            make.top.width.height.equalTo(giftView1)
            make.left.equalTo(giftView1.snp.right).offset(10)
        }
        
        
        back_image_view.addSubview(giftView3)
        giftView3.snp.makeConstraints { (make) in
            
            make.top.width.height.equalTo(giftView1)
            make.left.equalTo(giftView2.snp.right).offset(10)
        }
        
        back_image_view.addSubview(giftView4)
        giftView4.snp.makeConstraints { (make) in
            
            make.top.width.height.equalTo(giftView1)
            make.left.equalTo(giftView3.snp.right).offset(10)
        }
        
        back_image_view.addSubview(giftView5)
        giftView5.snp.makeConstraints { (make) in
            
            make.width.height.equalTo(giftView1)
            make.left.equalTo(giftView1).offset(35)
            make.top.equalTo(giftView1.snp.bottom).offset(10)
            
        }
        
        back_image_view.addSubview(giftView6)
        giftView6.snp.makeConstraints { (make) in
            
            make.top.width.height.equalTo(giftView5)
            make.left.equalTo(giftView5.snp.right).offset(10)
        }
        back_image_view.addSubview(giftView7)
        giftView7.snp.makeConstraints { (make) in
            
            make.top.width.height.equalTo(giftView5)
            make.left.equalTo(giftView6.snp.right).offset(10)
        }
        
        self.paddingData()
        
        
    }
    
    fileprivate func paddingData(){

        
        var resourceStr = "ST_老用户累计登陆"
        
        var prefixStr = "已累计登录 "
        
        if json["data"]["is_new_user"].boolValue{
            resourceStr = "ST_新人累计登陆"
            prefixStr = "已连续登录 "
        }
        
        if let url = Bundle.main.url(forResource: resourceStr, withExtension: "webp"){
            
            if let data = try? Data(contentsOf: url){
                back_image_view.image = UIImage.sd_image(withWebPData: data)
            }
        }
        
        
        
        
        
        
            self.daysLabel.text = prefixStr + json["data"]["sign_days"].stringValue + " 天"
            
            let array = json["data"]["list"].arrayValue.map { (itemJson) -> GiftCardViewModel in
                return GiftCardViewModel.init(fromJson: itemJson)
            }
            
            let giftViews =  [self.giftView1,self.giftView2,self.giftView3,self.giftView4,self.giftView5,self.giftView6,self.giftView7]
            
            for (idx,item) in giftViews.enumerated(){
                
                guard let data = array[safe:idx] else { continue }
                
                item.data = data
                
                item.index = idx + 1
                
                
                if data.signType == 4{
                    self.currGift = data
                }
            }
            
            let label = UILabel()
            
            let attrString = NSMutableAttributedString(string: json["data"]["bottom_remark"].stringValue)
            
            label.numberOfLines = 0
            
        
        
        let style = NSMutableParagraphStyle.create_line_spacing_paragraph_style(lineSpacing: 2)
        
        style.alignment = .center
        
            let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 13),.foregroundColor: UIColor(red: 0.7, green: 0.7, blue: 0.71, alpha: 1),.paragraphStyle:style]
            
            attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
            
            label.attributedText = attrString
            
            self.back_image_view.addSubview(label)
            label.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(48)
                make.right.equalToSuperview().offset(-48)
                make.bottom.equalToSuperview().offset(-92)
            }
       
        
    }
    
    //    MARK: - Properties
    
    fileprivate var currGift:GiftCardViewModel?
    
    var json = JSON.null
    
    fileprivate lazy var back_image_view:UIImageView = {
        let control = UIImageView()
        
//        control.isUserInteractionEnabled = true
        
        return control
    }()
    
    
    fileprivate lazy var confirm_btn:UIControl = {
        let btn = UIControl()
        
        
        btn.cornerRadius = 22
        
        let control = ST_FWGradientView()
        control.isUserInteractionEnabled = false
        control.bgLayer.startPoint = CGPoint(x: 0, y: 0)
        control.bgLayer.endPoint = CGPoint(x: 0, y: 1)
        control.bgLayer.colors = [UIColor.init(hex: 0xFFAB2A)!.cgColor,UIColor.init(hex: 0xFF8B2A)!.cgColor,UIColor.init(hex: 0xFF633F)!.cgColor]
        control.bgLayer.locations = [0,0.02,1]
        
        btn.addSubview(control)
        control.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        let label = UILabel()
        label.text = "领取"
        label.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        label.textAlignment = .center
        label.textColor = .white
        btn.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        btn.addTarget(self, action: #selector(get_gift_handle), for: UIControl.Event.touchUpInside)
        
        return btn
    }()
    
    
    @objc fileprivate func get_gift_handle(){
        
        guard let gift = currGift else { return  }
        
        JVrequest(PH.getLoginGiftApi,parameters: ["id":gift.id], success: { (json) in
            
            print("领取成功：：！！")
            
            ST_BTUserInfoManager.shared.modify_free_talk_count(value: json["data"]["free_quick_talk_num"].intValue)
            
            
            NotificationCenter.default.post(name: Notification.Name.push_peculiarity_success, object: nil)
            
            self.dismiss(animated: false) {
                
                let alert = ST_LoginGiftAnimationViewController(centerImageUrl: gift.image, awardsName: gift.name)
                
                
                GlobalPresent(toController: alert, animated: false)
            }
            
        }) { (code, err) in
            
            self.toast(text: err)
            
            main_thread_execute(afterDelay: 1.5) {
                self.dismiss(animated: false, completion: nil)
            }
        }
    }
    
    
    fileprivate lazy var daysLabel:UITextView = {
        
        let control = UITextView()
        control.isEditable = false
        control.isScrollEnabled = false
        control.textContainerInset = UIEdgeInsets.init(top: 2, left: 9, bottom: 2, right: 8)
        control.backgroundColor = UIColor.init(hex: 0xFF932E)
        control.textColor = .white
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.cornerRadius = 12
        return control
    }()
    
    
    fileprivate lazy var giftView1 = GiftCardView()
    fileprivate lazy var giftView2 = GiftCardView()
    fileprivate lazy var giftView3 = GiftCardView()
    fileprivate lazy var giftView4 = GiftCardView()
    fileprivate lazy var giftView5 = GiftCardView()
    fileprivate lazy var giftView6 = GiftCardView()
    fileprivate lazy var giftView7 = GiftCardView()
    
}
//MARK: -
fileprivate class GiftCardView: UIControl {
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        self.cornerRadius = 8
        
        self.addSubview(backView)
        backView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        self.addSubview(numberImageView)
        numberImageView.snp.makeConstraints { (make) in
            make.height.width.equalTo(22)
            make.top.left.equalToSuperview()
        }
        
        numberImageView.addSubview(indexLabel)
        indexLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalToSuperview().offset(4)
            make.width.equalTo(6)
            make.height.equalTo(14)
        }
        
        self.addSubview(doubleImageView)
        doubleImageView.snp.makeConstraints { (make) in
            make.width.equalTo(27)
            make.height.equalTo(14)
            make.right.top.equalToSuperview()
        }
        
        self.addSubview(icon_image_view)
        icon_image_view.snp.makeConstraints { (make) in
            make.width.equalTo(46)
            make.height.equalTo(46)
            make.top.equalToSuperview().offset(9)
            make.centerX.equalToSuperview()
        }
        
        
        
        self.addSubview(bottom_label)
        bottom_label.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.bottom.left.right.equalToSuperview()
        }
        
        
        self.addSubview(statusMaskView)
        statusMaskView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var normalColors = [UIColor.init(hex: 0xFFF1D2)!.cgColor,UIColor.init(hex: 0xFFF1D2)!.cgColor]
    
    fileprivate lazy var selectedColors = [UIColor.init(hex: 0xFFC55B)!.cgColor,UIColor.init(hex: 0xFF932E)!.cgColor]
    
    fileprivate lazy var backView:ST_FWGradientView = {
        let control = ST_FWGradientView()
        control.bgLayer.startPoint = CGPoint(x: 0, y: 0)
        control.bgLayer.endPoint = CGPoint(x: 0, y: 1)
        control.bgLayer.colors = normalColors
        return control
    }()
    
    fileprivate lazy var numberImageView:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("card_number_back"))
        return control
    }()
    
    fileprivate lazy var indexLabel:UILabel = {
        let control = UILabel()
        control.textColor = .white
        control.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var doubleImageView:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("double_icon"))
        control.isHidden = true
        return control
    }()
    
    
    fileprivate lazy var icon_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        return control
    }()
    
    fileprivate lazy var bottom_label:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleColor(UIColor.init(hex: 0xFF932E), for: UIControl.State.normal)
        control.setTitleColor(UIColor.white, for: UIControl.State.selected)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight.medium)
        control.backgroundColor = UIColor.init(white: 0, alpha: 0.1)
        return control
    }()
    
    
    fileprivate lazy var statusMaskView:ST_VerticalButton = {
        let control = ST_VerticalButton()
        control.backgroundColor = UIColor.init(white: 0, alpha: 0.6)
        control.image_view_edges = UIEdgeInsets.init(top: 13, left: 17, bottom: 38, right: 17)
        control.title_bottom_offset = -13
        control.isHidden = true
        return control
    }()
    
    
    var data:GiftCardViewModel?{
        didSet{
            
            guard let m = data else{
                return
            }
            
            icon_image_view.pin_setImage(from: m.image.url)
            
//            1 翻倍
            doubleImageView.isHidden = m.isDouble != 1
            
            bottom_label.setTitleForAllStates(m.name)
            
//            4:当前签到
            if m.signType == 4{
                
                backView.bgLayer.colors = self.selectedColors
                bottom_label.isSelected = true
                
                statusMaskView.isHidden = true
                
            }else{
                
                let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 11, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 1, green: 1, blue: 1, alpha: 1)]
                
//                1:已经签到
                if m.signType == 1{
                    
                    statusMaskView.setImageForAllStates(ST_ImageUtils.imageName("签到_已领取_icon")!)
                    
                    let attrString = NSMutableAttributedString(string: "已领取")
                    
                    attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
                    
                    statusMaskView.setTitleForAllStates(attrString)
                    statusMaskView.isHidden = false
                }
//               2:错过
                else if m.signType == 2{
                    
                    statusMaskView.setImageForAllStates(ST_ImageUtils.imageName("签到_已错过_icon")!)
                    
                    let attrString = NSMutableAttributedString(string: "已错过")
                    
                    attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
                    
                    statusMaskView.setTitleForAllStates(attrString)
                    
                    statusMaskView.isHidden = false
                }
//              3:待签到,
                else{
                    statusMaskView.isHidden = true
                }
                
                backView.bgLayer.colors = self.normalColors
                bottom_label.isSelected = false
                
            }
            
            
        }
    }
    
    var index = 1{
        didSet{
            indexLabel.text = index.string
        }
    }
    
}


//MARK: - Model
//以后台字段为准
class GiftCardViewModel : NSObject{

    var coin : Int
    var days : Int
    var id : Int
    var image : String
    var isDouble : Int
    var name : String
    var remark : String
    /**
     签到类型(1:已经签到,2:错过,3:待签到,4:当前签到)
     */
    var signType : Int
    var type : Int
    
    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        coin = json["coin"].intValue
        days = json["days"].intValue
        id = json["id"].intValue
        image = json["image"].stringValue
        isDouble = json["is_double"].intValue
        name = json["name"].stringValue
        remark = json["remark"].stringValue
        signType = json["sign_type"].intValue
        type = json["type"].intValue
        super.init()
    }
}
